﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Studio77.SuperLink.Core;
using Microsoft.Phone.Tasks;

namespace Studio77.SuperLink.Pages
{
    public partial class ClassifyPage : PhoneApplicationPage
    {
        private int currentIndex = 0;
        bool isNavigating = false;
        object navigationLock = new object();
        List<Grid> grids = new List<Grid>();

        public ClassifyPage()
        {
            InitializeComponent();
            //休闲模式
            grids.Add(this.gridScenery);
            //普通模式
            grids.Add(this.gridAnimal);
            //挑战模式
            grids.Add(this.gridCatoon);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            isNavigating = false;

            this.StoryboardStageImage.RepeatBehavior = RepeatBehavior.Forever;
            this.StoryboardStageImage.Begin();



            //读取关卡完成情况
            int sceneryStarSum = 0;
            for (int i = 1; i <= StageManager.ClassStageCount; i++)
            {
                string code = "1_" + i.ToString();
                if (StageManager.Instance.StageDatas.ContainsKey(code))
                {
                    sceneryStarSum += StageManager.Instance.StageDatas[code].StageLevel;
                }
            }
            this.txtSceneryComplete.Text = sceneryStarSum.ToString() + "/" + StageManager.ClassStageCount * 3;

            int animalStarSum = 0;
            for (int i = 1; i <= StageManager.ClassStageCount; i++)
            {
                string code = "2_" + i.ToString();
                if (StageManager.Instance.StageDatas.ContainsKey(code))
                {
                    animalStarSum += StageManager.Instance.StageDatas[code].StageLevel;
                }
            }
            this.txtAnimalComplete.Text = animalStarSum.ToString() + "/" + StageManager.ClassStageCount * 3;

            int cartoonStarSum = 0;
            for (int i = 1; i <= StageManager.ClassStageCount; i++)
            {
                string code = "3_" + i.ToString();
                if (StageManager.Instance.StageDatas.ContainsKey(code))
                {
                    cartoonStarSum += StageManager.Instance.StageDatas[code].StageLevel;
                }
            }
            this.txtCartoonComplete.Text = cartoonStarSum.ToString() + "/" + StageManager.ClassStageCount * 3;

            Dispatcher.BeginInvoke(() => { GotoMarketToComment(); });
        }

        /// <summary>
        /// 去市场评价
        /// </summary>
        private void GotoMarketToComment()
        {
            if (!StageManager.Instance.IsCommented &&
                ((StageManager.Instance.LaunchCount == 3) || StageManager.Instance.LaunchCount % 15 == 0))
            {
                if (MessageBox.Show("游戏还满意吗？去商店给个好评吧。谢谢您对77Game团队的支持！", "去评论吧！", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                    StageManager.Instance.IsCommented = true;
                }
                else
                {
                    StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;
                }
            }
        }

        void storyboard_Completed_Catoon(object sender, EventArgs e)
        {
            StageManager.Instance.CurrentStageType = "3";
            NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?StageType=3", UriKind.Relative));
        }

        void storyboard_Completed_Animal(object sender, EventArgs e)
        {
            StageManager.Instance.CurrentStageType = "2";
            NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?StageType=2", UriKind.Relative));
        }

        void storyboard_Completed_Scenery(object sender, EventArgs e)
        {
            StageManager.Instance.CurrentStageType = "1";
            NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?StageType=1", UriKind.Relative));
        }

        private double GetTranX(UIElement ele)
        {
            return (ele.RenderTransform as CompositeTransform).TranslateX;
        }

        private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.Angle > 135 && e.Angle < 225)  //向左增加图片 
            {
                TurnLeft();
                SoundManager.PlayEffect(SoundManager.Switch_Classify);
            }
            else if (e.Angle > 315 || e.Angle < 45)//向右增加图片 
            {
                TurnRight();
                SoundManager.PlayEffect(SoundManager.Switch_Classify);
            }
        }

        private void TurnLeft()
        {
            currentIndex++;
            if (currentIndex >= 3)
            {
                currentIndex = 2;
            }
            //currentIndex = currentIndex % 3;
            for (int i = 0; i < grids.Count; i++)
            {
                Grid item = grids[i];
                double nextTranX = (i - currentIndex) * 480;
                DoTranXAnimation(item, nextTranX);
            }

        }

        private void TurnRight()
        {
            currentIndex--;
            if (currentIndex < 0)
            {
                currentIndex = 0;
            }
            //if (currentIndex < 0)
            //{
            //    currentIndex = 2;
            //}
            for (int i = 0; i < grids.Count; i++)
            {
                Grid item = grids[i];
                double nextTranX = (i - currentIndex) * 480;
                DoTranXAnimation(item, nextTranX);
            }
        }

        private static void DoTranXAnimation(Grid item, double nextTranX)
        {
            BounceEase be = new BounceEase();
            be.Bounces = 2;
            be.Bounciness = 5;
            DoubleAnimation xAnimation = new DoubleAnimation
            {
                To = nextTranX,
                Duration = TimeSpan.FromSeconds(0.5),
                EasingFunction = be
            };
            Storyboard.SetTargetProperty(xAnimation, new PropertyPath("TranslateX"));

            Storyboard storyboard = new Storyboard();
            Storyboard.SetTarget(storyboard, item.RenderTransform);
            storyboard.Children.Add(xAnimation);

            storyboard.Begin();
        }

        private static Storyboard ClickAnimation(Grid aimGird)
        {
            DoubleAnimation scaleXAnimation = new DoubleAnimation
            {
                From = 1.1,
                To = 1,
                Duration = TimeSpan.FromSeconds(0.5),
                EasingFunction = new QuarticEase()
            };
            DoubleAnimation scaleYAnimation = new DoubleAnimation
            {
                From = 1.1,
                To = 1,
                Duration = TimeSpan.FromSeconds(0.5),
                EasingFunction = new QuarticEase()
            };

            Storyboard.SetTargetProperty(scaleXAnimation, new PropertyPath("ScaleX"));
            Storyboard.SetTargetProperty(scaleYAnimation, new PropertyPath("ScaleY"));
            Storyboard storyboard = new Storyboard();
            Storyboard.SetTarget(storyboard, aimGird.RenderTransform);
            storyboard.Children.Add(scaleXAnimation);
            storyboard.Children.Add(scaleYAnimation);
            return storyboard;
        }

        /// <summary>
        /// 休闲模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SceneryImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

            lock (navigationLock)
            {
                if (!isNavigating)
                {
                    this.StoryboardStageImage.Stop();
                    isNavigating = true;
                    SoundManager.PlayEffect(SoundManager.Click_Button);
                    Storyboard storyboard = ClickAnimation(gridScenery);
                    storyboard.Completed += new EventHandler(storyboard_Completed_Scenery);
                    storyboard.Begin();
                }
            }
        }


        /// <summary>
        /// 普通模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AnimalImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            lock (navigationLock)
            {
                if (!isNavigating)
                {
                    isNavigating = true;
                    SoundManager.PlayEffect(SoundManager.Click_Button);
                    Storyboard storyboard = ClickAnimation(gridAnimal);
                    storyboard.Completed += new EventHandler(storyboard_Completed_Animal);
                    storyboard.Begin();
                }
            }
        }

        /// <summary>
        /// 挑战模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CartoonImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            lock (navigationLock)
            {
                if (!isNavigating)
                {
                    isNavigating = true;
                    SoundManager.PlayEffect(SoundManager.Click_Button);
                    Storyboard storyboard = ClickAnimation(gridCatoon);
                    storyboard.Completed += new EventHandler(storyboard_Completed_Catoon);
                    storyboard.Begin();
                }
            }
        }
    }
}